package NETWORK;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-14
 * Time: 11:17
 */
public class UdpClient {

    DatagramSocket socket = null;

    //服务器不需要指定端口号==>发送时填写服务器端口号就行==>证明要将请求发送给服务器
    //服务器在作出响应
    public UdpClient() throws SocketException {
        socket = new DatagramSocket();
    }

    //客户端启动
    public void start() throws IOException {
        System.out.println("客户端启动!!!");
        while(true){
            //客户需要输入数据做出请求
            Scanner scan = new Scanner(System.in);
            System.out.print(">");
            String request = scan.next();
            //将请求打包成一个数据报发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName("127.0.0.1"),8000);
            socket.send(requestPacket);
            //客户端发送请求,服务器作出响应返回给客户端
            //客户端接收响应

            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            //根据响应结果,给用户显示
            System.out.printf("request : %s ; response : %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient udpClient = new UdpClient();
        udpClient.start();
    }



}
